
import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, Animated, View, Image, TouchableOpacity, Alert
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ApprovalCpt } from '../_components/ApprovalCpt';
import MethodUtil from '../../../utils/MethodUtil';
import ToastUtil from '../../../utils/toast';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';

const scale = GLOBAL.SCALE;
const correct = require('../../../imgs/global/correct.png')
const arrowIcon = require('../../../imgs/order/down.png')

export class NonWholePackList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '成交申请列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		let { bidPackageId, periodNum, salesType } = props.navigation.state.params || {};
		// bidPackageId = 'PKG2008180000058'
		this.state = {
			status: 'data',
			refreshIcon: false,
			listData: [],
			allText: '',
			imgObj: new Animated.Value(0)
		}
		this.pageParams = {
			bidPackageId
		}
		this.applyParams = {
			applyInfo: {
				applyType: '',
				bizModel: 'Z',
				winRule: 'SINGLE',
				salesType,
				bidPackageId,
				periodNum
			},
			itemList: []
		}
		this.salesType = salesType
		this.selectData = {};
	}

	async componentWillMount() {
		await this.initPage();
	}
	//初始化数据
	initPage = async () => {
		this.setState({
			status: 'loading',
			refreshIcon: true
		})
		let res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_RES_LIST), this.pageParams);
		if (res) {
			this.setState({
				listData: res,
				status: res ? 'data' : 'empty',
				refreshIcon: false,
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}
	resetData = (res, index) => {
		let { listData } = this.state
		listData[index] = res
		let appOrderDetails = []
		listData[index].appOrderDetailsVTOS.map(item => {
			if (item.select) {
				appOrderDetails.push(item)
			}
		})
		listData[index].showItem = false;
		listData[index].boxHeight = new Animated.Value(384 * scale);
		listData[index].openHeight = 0;
		if (appOrderDetails && appOrderDetails.length > 0) {
			listData[index].openHeight = 128 * appOrderDetails.length
		} else {
			appOrderDetails = []
		}
		this.setState({
			listData
		}, () => {
			this.bottomText()
		})
	}
	changeCheck = (index) => {
		let { listData, isAll } = this.state;
		listData[index].selectList = !listData[index].selectList
		let num = 0
		listData.map((item, i) => {
			if (item.selectList) {
				num++
			}
		})
		if (num === listData.length) {
			isAll = true
		}
		else {
			isAll = false
		}
		this.setState({
			listData, isAll
		}, () => {
			this.bottomText()
		});
	}
	//全选方法
	_selectAll = (isAll) => {
		let { listData } = this.state;
		listData.map((item) => {
			item.selectList = isAll
		})
		this.setState({
			listData,
			isAll
		}, () => {
			this.bottomText()
		});
	}
	bottomText = () => {
		let { listData } = this.state;
		let num = 0, qty = 0, allText;
		listData.map((item) => {
			if (item.selectList) {
				num++;
				item.appOrderDetailsVTOS.map(i => {
					if (i.select) {
						qty += i.intentionQuantity
					}
				})
			}
		})
		if (num == 0 || allText == 0) {
			allText = ''
		}
		else {
			allText = '选择' + num + '条,' + qty + '吨'
		}

		this.setState({
			allText
		})
	}
	_refused = () => {
		this.applyParams.applyInfo.applyType = 'REJECT'
		this._showAlert()

	}
	_agree = () => {
		this.applyParams.applyInfo.applyType = 'ACCEPT'
		this._showAlert()
	}
	_showAlert = async () => {
		let { listData } = this.state;
		this.applyParams.itemList = []
		listData.map((item) => {
			if (item.selectList) {
				item.appOrderDetailsVTOS.map((i, j) => {
					if (i.select) {
						this.applyParams.itemList.push(
							{
								bidOrderId: i.bidOrderId,
								intentionQuantity: i.intentionQuantity,
								resourceId: i.resourceId
							}
						)
					}
				})
			}
		})
		if (this.applyParams.itemList.length === 0) {
			ToastUtil.showWarning('请选择成交对象');
			return
		}
		let responese = await HTTP.POST(API_GENERATE(API.PACKAGE_TOAST), this.applyParams);
		if (responese) {
			this.priceCheckMsg = responese.priceCheckMsg
			this.setState({
				showRejectModal: true
			})
		}
	}
	//成交
	approve = async () => {
		this.setState({
			showRejectModal: false,
			status: 'loading'
		})
		let res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_APPLY), this.applyParams);
		if (res) {
			this.setState({
				status: 'data',
			}, () => {
				ToastUtil.showSuccess(this.applyParams.applyInfo.applyType === 'ACCEPT' ? '审批成功' : '驳回成功').then(() => {
					this._goBack();
				})
			})
		}
		else {
			this.setState({
				status: 'data',
			})
		}
	}
	_goBack = () => {
		this.props.navigation.navigate('ClinchRecord', {
			bidPackageId: this.pageParams.bidPackageId, bizModel: 'Z', winRule: 'SINGLE', salesType: this.salesType
		})
	}
	// 商品展开和隐藏
	toggleProduct = (index, currentHeight, openHeight) => {
		let { listData, imgObj } = this.state;
		listData[index].showItem = !listData[index].showItem;
		Animated.spring(currentHeight, {
			duration: 300,
			toValue: listData[index].showItem ? openHeight * scale : 384 * scale,
		}).start();
		Animated.timing(imgObj, { toValue: listData[index].showItem ? 1 : 0, duration: 300 }).start()
	}

	_renderListItem = (data, index) => {
		let upDegreen = require('../../../imgs/my-siter/up.png');
		let downDegreen = require('../../../imgs/my-siter/down.png');
		let { priceType, appOrderDetailsVTOS, chineseName, custPurNum, offerBottomPrice, suggestedPrice, boxHeight, udPrice, areaIdName } = data
		let appOrderDetails = [], qualitySum = 0
		appOrderDetailsVTOS.map(item => {
			if (item.select) {
				item.intentionQuantity = Number(item.intentionQuantity)
				appOrderDetails.push(item)
				qualitySum += item.intentionQuantity
			}
		})
		let { imgObj } = this.state;
		const spin = imgObj.interpolate({
			inputRange: [0, 1],//输入值
			outputRange: ['0deg', '180deg'] //输出值
		})
		return (
			<View style={styles.itemBox}>
				<View style={styles.itemTop}>
					<View style={styles.itemTitle}>
						<TouchableOpacity style={styles.itemTopLeft} onPress={() => this.changeCheck(index)}>
							<View style={styles.checkBox}>
								<View style={styles.lockView}>
									{
										data.selectList ? <Image style={styles.lockImage} source={correct} /> : null
									}
								</View>
							</View>
							<Text style={{ color: '#040404', fontWeight: '600' }}>{chineseName}</Text>
						</TouchableOpacity>
						<TouchableOpacity onPress={() => {
							this.props.navigation.navigate('NonWholePackDetail', {
								data,
								applyInfo: this.applyParams.applyInfo,
								salesType: this.salesType,
								callback: (res) => this.resetData(res, index)
							})
						}}>
							<Text style={{ fontSize: 12 * scale, color: "#0091FF" }}>[添加/编辑成交信息]</Text>
						</TouchableOpacity>
					</View>
					<View style={[styles.itemTitle, { paddingLeft: 10 * scale, marginTop: 12 * scale }]}>
						<Text style={styles.titleText}>数量 {custPurNum || '-'} 吨</Text>
						<View style={{ flexDirection: "row", alignItems: 'center' }}>
							{priceType == 1 ?
								<Text style={styles.titleText}>报盘底价 ¥ {MethodUtil.toThousands(offerBottomPrice || 0, 2) || '-'} 元/吨 </Text> :
								<Text style={styles.titleText}>{udPrice > 0 ? '+' : ''}¥{MethodUtil.toThousands(udPrice || 0, 2)} 元/吨 </Text>
							}
							<Text style={[styles.priceType, priceType == 2 ? { color: '#FA6400', backgroundColor: '#FBEFE8' } : { color: '#85C0EC', backgroundColor: '#ECF7FF' }]}>
								{priceType == 2 ? '升贴水' : '一口价'}
							</Text>
						</View>
					</View>
					<View style={[styles.itemTitle, { paddingLeft: 10 * scale, marginTop: 12 * scale }]}>
						{suggestedPrice && priceType == 1 ?
							<Text style={styles.titleText}>{areaIdName}现货价：¥{suggestedPrice ? MethodUtil.toThousands(suggestedPrice || '0') : null}/吨 </Text>
							: null
						}
					</View>
				</View>
				<Animated.View style={[styles.itemMiddle, appOrderDetails.length > 3 ? { height: boxHeight, overflow: 'hidden' } : null]}>
					{appOrderDetails.length > 0 ?
						appOrderDetails.map((item, index) => {
							let price
							if (priceType == 2) {
								price = item.udPrice
							}
							else {
								price = item.price
							}
							return (
								<View key={index} style={styles.costBox}>
									<Text style={{ fontSize: 12 * scale }}>{item.companyName}</Text>
									<View style={styles.costItem}>
										<Text style={[styles.costTextLeft, { marginRight: 40 * scale }]}>成交单价</Text>
										<Text style={styles.costNum}>{MethodUtil.toThousands(price || 0, 2) || '-'}</Text>
										<Text style={styles.costTextLeft}>元/吨</Text>
										{suggestedPrice && priceType == 1 ?
											<View style={styles.costTableRight}>
												<Image source={price - suggestedPrice > 0 ? upDegreen : downDegreen} style={styles.priceFlag} />
												<Text style={price - suggestedPrice > 0 ? styles.tableUpText : styles.tableDownText}>{Math.abs(price - suggestedPrice)}</Text>
											</View>
											: null
										}
									</View>
									<View style={styles.costItem}>
										<Text style={[styles.costTextLeft, { marginRight: 40 * scale }]}>报盘数量</Text>
										<Text style={styles.costNum}>{item.quantity}</Text>
										<Text style={styles.costTextLeft}>吨</Text>
									</View>
									<View style={styles.costItem}>
										<Text style={[styles.costTextLeft, { marginRight: 40 * scale, color: "#CA0202", marginLeft: -5 * scale }]}>*成交数量</Text>
										<Text style={styles.costNumInput}>{item.intentionQuantity}</Text>
										<Text style={styles.costTextLeft}>吨</Text>
									</View>
								</View>
							)
						})
						:
						<View style={{ paddingVertical: 10 * scale }}>
							<Text>暂无成交意向</Text>
						</View>
					}
				</Animated.View>
				{
					appOrderDetails && appOrderDetails.length > 3 ? (
						<TouchableOpacity activeOpacity={1} style={styles.toggleImg} onPress={() => this.toggleProduct(index, data.boxHeight, data.openHeight)}>
							<Animated.Image style={[styles.downImg, { transform: [{ rotateX: spin }] }]} source={arrowIcon} ></Animated.Image>
							<Text style={{ fontSize: 10 * scale, color: '#0091FF', marginTop: 10 * scale }}>查看更多</Text>
						</TouchableOpacity>
					) : null
				}
				{appOrderDetails.length > 0 ?
					<View style={styles.itemBottom}>
						<Text style={{ fontSize: 12 * scale }}>合同意向{appOrderDetails.length}项，总量：{qualitySum}吨</Text>
					</View> : null
				}
			</View>
		)
	}
	render() {
		let { listData, refreshIcon, status, isAll, allText, showRejectModal } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.body}>
					<FlatList
						data={listData}
						renderItem={({ item, index }) => this._renderListItem(item, index)}
						refreshing={refreshIcon}
						onRefresh={() => { this.initPage() }}
					/>
					<ApprovalCpt
						data={{ isAll, allText }}
						method={{ selectAll: this._selectAll, refused: this._refused, agree: this._agree }}
					/>
				</View>
				{status !== 'data' ?
					<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
						<PageStatusIndex status={status} onErrorPress={() => { this.initPage() }} />
					</View> : null
				}
				<RefuseModal
					titleText={this.applyParams.applyInfo.applyType == 'ACCEPT' ? '成交理由' : '拒绝理由'}
					placeholderText={this.applyParams.applyInfo.applyType == 'ACCEPT' ? '请输入成交原因' : '请输入驳回原因'}
					visible={showRejectModal}
					btnPress={(comments) => {
						this.applyParams.applyInfo.remark = comments;
						this.approve();
					}}
					text={this.priceCheckMsg}
					bgPress={() => {
						this.setState({
							showRejectModal: false,
						});
					}} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	body: {
		flex: 1,
		backgroundColor: '#E8ECF5',
	},
	itemBox: {
		marginTop: 20 * scale,
		backgroundColor: '#fff',
		borderRadius: 6 * scale,
		marginHorizontal: 20 * scale
	},
	itemTop: {
		paddingVertical: 10 * scale,
		paddingRight: 10 * scale,
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale
	},
	itemTitle: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
	},
	itemTopLeft: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	lockView: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		height: 12 * scale,
		width: 12 * scale,
		borderWidth: 1 * scale,
		borderColor: style.color.themeColor,
		marginRight: 10 * scale,
		marginLeft: 10 * scale
	},
	lockImage: {
		tintColor: style.color.themeColor,
		width: 8 * scale,
		height: 8 * scale,
		marginLeft: 1 * scale
	},
	imgStyle: {
		tintColor: '#000',
		width: 10 * scale,
		height: 6 * scale,
		transform: [{ rotate: '-90deg' }]
	},
	itemBottom: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		paddingTop: 10 * scale,
		paddingBottom: 12 * scale,
		paddingHorizontal: 10 * scale,
	},
	priceType: {
		fontSize: 10,
		paddingVertical: 2,
		paddingHorizontal: 5,
		backgroundColor: '#FBEFE8',
		marginLeft: 5 * scale
	},
	titleText: {
		color: '#000',
		fontSize: 11 * scale,
		fontWeight: '600'
	},
	itemMiddle: {
		// paddingVertical: 10 * scale,
		paddingHorizontal: 10 * scale,
	},
	priceFlag: {
		width: 6,
		height: 10,
		marginRight: 3
	},
	tableUpText: {
		fontSize: 10,
		color: '#E02020'
	},
	tableDownText: {
		fontSize: 10,
		color: '#56C910'
	},
	costTableRight: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'center',
		marginRight: 16
	},
	costItem: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingLeft: 40 * scale,
		marginTop: 13 * scale
	},
	costBox: {
		paddingVertical: 12 * scale,
		borderBottomWidth: 1 * scale,
		borderBottomColor: '#E3E7F0',
		height: 128 * scale
	},
	costTextLeft: {
		fontSize: 12 * scale,
		color: '#000',
		marginRight: 10 * scale
	},
	costNum: {
		fontSize: 12 * scale,
		color: '#000',
		opacity: 0.78,
		width: 80 * scale
	},
	costNumInput: {
		color: '#000',
		fontWeight: '600',
		width: 80 * scale
	},
	toggleImg: {
		width: '100%',

		marginVertical: 10 * scale,
		alignItems: "center",
		justifyContent: 'center'
	},
	downImg: {
		width: 12 * scale,
		height: 12 * scale
	},
})